package com.example.shop.controller;

import com.alibaba.fastjson.JSON;
import com.example.shop.pojo.Logs;
import com.example.shop.pojo.User;
import com.example.shop.pojo.UserAuth;
import com.example.shop.pojo.UserDto;
import com.example.shop.service.UserAuthService;
import com.example.shop.service.UserService;
import com.example.shop.utils.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {
	// 日志对象
	private final static Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private LogsRecord logsRecord;
	@Autowired
	private UserAuthService userAuthService;

	UserController() {

	}

	/**
	 * 用户注册
	 *
	 * @throws Exception
	 */
	@PostMapping("/register")
	public String register(@RequestBody User user) throws Exception {

		AutoLogout.userPerformedOperation(user.getAccount());
		/*
		 * if(userService.register(user)) { return new
		 * Result<>(10001,"success",userService.register(user)); }
		 *
		 * return new Result<>(10000,"fail",userService.register(user));
		 */
		// 赋予员工对应身份信息
		userAuthService.giveBaseAuth(user);

		return userService.register(user);
	}

	/**
	 * 普通用户登录
	 */
	@GetMapping("/login")
	public Result<String> login(@RequestBody User user) {
		// 记录日志
		String msg = user.getAccount() + "普通用户登录";
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_LOGIN, msg));

		String result = userService.login(user);
		AutoLogout.autoLogout(user);
		return new Result<>(10000, "", result);
	}

	/**
	 * 用户信息认证1:姓名、身份证验证
	 * 
	 * @throws IOException
	 */
	@PostMapping("/auth/userInfo1")
	public Result<String> infoAuthentication1(@RequestBody UserDto userDto) throws IOException {
		// 登录校验
		Object employee = UserIdSession.getAttribute(userDto.getAccount());
		if (employee == null) {
			return Result.fail("NOTLOGIN");
		}

		// 记录用户操作
		AutoLogout.userPerformedOperation(userDto.getAccount());

		// 记录日志
		String msg = userDto.getAccount() + "用户信息认证1:姓名" + userDto.getUserName() + ",身份证验证" + userDto.getIdentityCard();
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_SELECT, msg));

		String result = userService.infoAuthentication1(userDto);
		if ("用户信息认证成功".equals(result)) {
			return new Result<>(10001, "success", result);
		}
		return new Result<>(10000, "fail", result);
	}

	/**
	 * 用户信息认证2:姓名、学历验证
	 */
	@PostMapping("/auth/userInfo2")
	public Result<String> infoAuthentication2(@RequestBody UserDto userDto, HttpServletResponse response) {
//    	//登录校验
//   	 Object employee = UserIdSession.getAttribute(userDto.getAccount());
//		if (employee == null) {
//			return Result.fail("NOTLOGIN");
//		}
		// 记录日志
		String msg = userDto.getAccount() + "用户信息认证2:姓名" + userDto.getUserName() + "、学历验证" + userDto.getEducationId();
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_SELECT, msg));

		AutoLogout.userPerformedOperation(userDto.getAccount());

		String result = userService.infoAuthentication2(userDto);
		if ("用户信息认证成功".equals(result)) {
			return new Result<>(10001, "success", result);
		}
		return new Result<>(10000, "fail", result);
	}

	/**
	 * 用户信息认证3:有无犯罪记录
	 */
	@PostMapping("/auth/userInfo3")
	public Result<String> infoAuthentication3(@RequestBody UserDto userDto) {
		// 登录校验
		Object employee = UserIdSession.getAttribute(userDto.getAccount());
		if (employee == null) {
			return Result.fail("NOTLOGIN");
		}
		// 记录日志
		Long criminal = userDto.getCriminalRecord();
		String criminalRecord = "";
		if (criminal == 0L) {
			criminalRecord = "没有犯罪记录";
		} else {
			criminalRecord = "有犯罪记录";
		}
		// 记录日志
		String msg = userDto.getAccount() + "用户信息认证3:" + criminalRecord;
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_SELECT, msg));

		AutoLogout.userPerformedOperation(userDto.getAccount());

		return new Result<>(10001, "success", userService.infoAuthentication3(userDto));
	}

	/**
	 * 用户信息认证4:姓名、身份证、银行卡验证
	 */
	@PostMapping("/auth/userInfo4")
	public Result<String> infoAuthentication4(@RequestBody UserDto userDto) {
		// 登录校验
		Object employee = UserIdSession.getAttribute(userDto.getAccount());
		if (employee == null) {
			return Result.fail("NOTLOGIN");
		}
		// 记录日志
		String msg = userDto.getAccount() + "用户信息认证4:姓名" + userDto.getUserName() + "、身份证" + userDto.getIdentityCard()
				+ "、银行卡" + userDto.getBankCardNumber();
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_SELECT, msg));

		AutoLogout.userPerformedOperation(userDto.getAccount());

		String result = userService.infoAuthentication4(userDto);
		if ("用户信息认证成功".equals(result)) {
			return new Result<>(10001, "success", result);
		}
		return new Result<>(10000, "fail", result);
	}

	/**
	 * 用户信息认证5:姓名、身份证、手机号验证
	 */
	@PostMapping("/auth/userInfo5")
	public Result<String> infoAuthentication5(@RequestBody UserDto userDto) {
		// 登录校验
		Object employee = UserIdSession.getAttribute(userDto.getAccount());
		if (employee == null) {
			return Result.fail("NOTLOGIN");
		}
		// 记录日志
		String msg = userDto.getAccount() + "用户信息认证5:姓名" + userDto.getUserName() + "、身份证" + userDto.getIdentityCard()
				+ "、手机号验证" + userDto.getIphoneNum();
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_SELECT, msg));

		AutoLogout.userPerformedOperation(userDto.getAccount());

		String result = userService.infoAuthentication5(userDto);
		if ("用户信息认证成功".equals(result)) {
			return new Result<>(10001, "success", result);
		}
		return new Result<>(10000, "fail", result);
	}

	/**
	 * 用户更新信息
	 */
	@PutMapping("/update")
	public Result<String> updateInfo(@RequestBody UserDto user) {
		// 登录校验
		Object employee = UserIdSession.getAttribute(user.getAccount());
		if (employee == null) {
			return Result.fail("NOTLOGIN");
		}

		// 记录用户操作
		AutoLogout.userPerformedOperation(user.getAccount());

		// 权限校验
		List<UserAuth> userAuthLists = new ArrayList<UserAuth>();
		userAuthLists.add(new UserAuth(user.getAccount(), 2L, 0L));
		String userAuthResult = userAuthService.checkAuth(userAuthLists);
		if (!"权限验证通过".equals(userAuthResult)) {
			return Result.fail(userAuthResult);
		}
		;

		// 记录日志
		String msg = user.getAccount() + "用户更新信息: " + user.toString();
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_OPERATION, msg));

		String result = userService.updateInfo(user, user.getCode());
		if ("用户成功更新信息".equals(result)) {
			return new Result<>(10001, "success", result);
		}
		return new Result<>(10000, "fail", result);
	}

	/**
	 * 用户查询
	 */
	@GetMapping("/select")
	public Result<User> selectUser(@RequestBody UserDto user) {
		// 记录用户操作
		AutoLogout.userPerformedOperation(user.getAccount());

		// 权限校验
		List<UserAuth> userAuthLists = new ArrayList<UserAuth>();
		userAuthLists.add(new UserAuth(user.getAccount(), 3L, 0L));
		String userAuthResult = userAuthService.checkAuth(userAuthLists);
		if (!"权限验证通过".equals(userAuthResult)) {
			return Result.fail(userAuthResult);
		}
		;

		// 记录日志
		String msg = user.getAccount() + "用户更新信息: " + user.toString();
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_OPERATION, msg));

		// 用户查询
		User result = userService.selectUser(user);
		if (result == null) {
			Result.fail(result);
		}
		return Result.success(result);
	}

	/**
	 * 用户退出
	 */
	@GetMapping("/logout")
	public Result<String> logout(String account) {
		// 登录校验
		Object employee = UserIdSession.getAttribute(account);
		if (employee == null) {
			return Result.fail("NOTLOGIN");
		}
		// 记录日志
		String msg = account + "用户退出:";
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_OPERATION, msg));

		UserIdSession.removeAttribute(account);
		return Result.success("用户退出");
	}

	/**
	 * 发送短信验证码
	 *
	 * @param user
	 * @param
	 */
	@PostMapping("/sendMsg")
	public String sendMsg(@RequestBody User user) {
		// 生成验证码
		String code = ValidateCodeUtils.generateValidateCode(4).toString();
		System.out.print(code);
		// 记录用户操作
		AutoLogout.userPerformedOperation(user.getAccount());

		// 记录日志
		String msg = user.getAccount() + "用户发送验证码: " + code;
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_OPERATION, msg));

		// 发送短信
		/* SMSUtils.sendMessage("","",user.getPhone(),code); */

		// 将短信验证码存到session中()
		UserIdSession.setAttribute(user.getIphoneNum().toString(), code);
//        //将短信验证码存到redis中
//       redisTemplate.opsForValue().set("login_"+user.getPhone(),code,60, TimeUnit.SECONDS);
		return code;
	}

	/**
	 * 赋予员工权限
	 */
	@GetMapping("/give/auth")
	public Result<String> giveAuth(@RequestBody List<UserAuth> userAuths) {
		UserAuth currentUserAuth = userAuths.get(0);

		// 登录校验
		Object employee = UserIdSession.getAttribute(currentUserAuth.getUserAccount());
		if (employee == null) {
			return Result.fail("NOTLOGIN");
		}

		// 记录用户操作
		AutoLogout.userPerformedOperation(currentUserAuth.getUserAccount());

		// 记录日志
		String msg = currentUserAuth.getUserAccount() + "赋予员工权限";
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_OPERATION, msg));

		String result = userAuthService.giveAuth(currentUserAuth, userAuths.subList(1, userAuths.size()));
		if ("赋予权限成功".equals(result)) {
			return Result.success(result);
		}
		return Result.fail(result);
	}
}
